package com.huike.web.controller.business;

import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.domain.TbClue;
import com.huike.clues.service.ISysDictDataService;
import com.huike.common.annotation.Log;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.enums.BusinessType;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商机跟进记录Controller
 * @date 2021-04-28
 */
@RestController
@RequestMapping("/business/record")
public class TbBusinessTrackRecordController extends BaseController {

    @Autowired
    private ITbBusinessTrackRecordService tbBusinessTrackRecordService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询商机跟进记录列表
     * 这个里面存在了一个key_items所以需要在列表中将数据中取出来
     *
     */
    @PreAuthorize("@ss.hasPermi('business:record:list')")
    @GetMapping("/list")
    public  AjaxResult list(@RequestParam("businessId")Long id){
        List<TbBusinessTrackRecord> businessTrackRecordList = tbBusinessTrackRecordService.getBusinessTrackRecordList(id);
        for (TbBusinessTrackRecord tbBusinessTrackRecord : businessTrackRecordList) {
            String[] keyItems = tbBusinessTrackRecord.getKeyItems().split(",");
            for (String keyItem : keyItems) {
                String dictLabel=sysDictDataService.selectDictLabel("communication_point",keyItem);
                tbBusinessTrackRecord.getKeys().add(dictLabel);
            }
        }
        return AjaxResult.success(businessTrackRecordList);
    }

    /**
     * 新增商机跟进记录,
     * 同样的，这里涉及到两个对象，一个是商机跟进对象，还有一个是商机对象，一个insert 一个update
     */
    @PreAuthorize("@ss.hasPermi('business:record:add')")
    @Log(title = "商机跟进记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbBusinessTrackRecord businessTrackVo){
        TbBusinessTrackRecord tbBusinessTrackRecord = new TbBusinessTrackRecord();
        BeanUtils.copyProperties(businessTrackVo,tbBusinessTrackRecord);
        tbBusinessTrackRecord.setCreateBy(SecurityUtils.getUsername());
        tbBusinessTrackRecord.setCreateTime(DateUtils.getNowDate());
        TbBusiness business = new TbBusiness();
        BeanUtils.copyProperties(businessTrackVo,business);
        business.setId(tbBusinessTrackRecord.getBusinessId());
        // 商机和线索的状态一致，统一为跟进中
        business.setStatus(TbClue.StatusType.FOLLOWING.getValue());
        return  toAjax(tbBusinessTrackRecordService.insert(businessTrackVo,business));

    }
}